package io.github.guojiaxing1995.easyJmeter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.github.guojiaxing1995.easyJmeter.common.enumeration.JmeterStatusEnum;
import io.github.guojiaxing1995.easyJmeter.mapper.TaskLogMapper;
import io.github.guojiaxing1995.easyJmeter.model.TaskLogDO;
import io.github.guojiaxing1995.easyJmeter.service.TaskLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TaskLogServiceImpl implements TaskLogService {

    @Autowired
    private TaskLogMapper taskLogMapper;

    @Override
    public List<TaskLogDO> getTaskLog(String taskId, Integer jCase, JmeterStatusEnum status, String address,  Boolean result) {
        return taskLogMapper.search(taskId,jCase,status,address,result);
    }

    @Override
    public boolean createTaskLog(TaskLogDO taskLogDO) {
        return taskLogMapper.insert(taskLogDO) > 0;
    }

    @Override
    public boolean updateTaskLog(TaskLogDO taskLogDO, Boolean result) {
        taskLogDO.setResult(result);
        return taskLogMapper.updateById(taskLogDO) > 0;
    }
    
    @Override
    public List<Map<String, Object>> getTaskLogByTaskId(String taskId) {
        QueryWrapper<TaskLogDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("status as status, min(DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s')) as create_time").eq("task_id", taskId).groupBy("status");
        List<Map<String, Object>> levelList = taskLogMapper.selectMaps(queryWrapper);
        for (Map<String, Object> level : levelList) {
            QueryWrapper<TaskLogDO> query = new QueryWrapper<>();
            query.select("*").eq("task_id", taskId).eq("status", level.get("status"));
            List<TaskLogDO> taskLogDOS = taskLogMapper.selectList(query);
            level.put("logs", taskLogDOS);
            JmeterStatusEnum status = JmeterStatusEnum.getEnumByCode((Integer) level.get("status"));
            level.put("status", status);
        }
        log.info(levelList.toString());
        return levelList;
    }
}
